package excel

import (
	"fmt"
	"github.com/xuri/excelize/v2"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"time"
)

type ExcelFiles struct {
	allFiles []string
}

func NewExcelFiles() *ExcelFiles {
	return &ExcelFiles{}
}

func (ef *ExcelFiles) DirFiles(root string) {

	err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			fmt.Println("DirFiles func Walk err", err)
			return err
		}
		if !info.IsDir() {
			ef.allFiles = append(ef.allFiles, path)
		}

		return nil
	})

	if err != nil {
		fmt.Println("DirFiles func return", err)
		panic("excel2go DirFiles err")
	}

}

func (ef *ExcelFiles) GetFiles() []string {
	return ef.allFiles
}

func ExportExcel(pack bool, excelDir string, jsonDir string, goDir string) {
	eg := NewExcelFiles()
	eg.DirFiles(excelDir)

	fmt.Println("files num", len(eg.GetFiles()))
	allFiles := eg.GetFiles()
	startTime := time.Now()
	var wg sync.WaitGroup
	wg.Add(len(allFiles))
	for _, vname := range allFiles {
		go func(vname string) {
			defer wg.Done()
			f, err := excelize.OpenFile(vname)

			if err != nil {
				fmt.Println(err)
				return
			}
			defer func() {
				if err := f.Close(); err != nil {
					fmt.Println(err)
				}
			}()

			excelName := filepath.Base(vname)
			extName := filepath.Ext(excelName)
			filenameOnly := strings.TrimSuffix(excelName, extName)
			var allData [][]string
			allKeys := make(map[int]string)
			allFieldTypes := make(map[string][]string)
			if excelName == "constdefine.xlsx" { //特殊配置文件特别处理
				allSpecFieldTypes := make(map[string][]string)
				for _, name := range f.GetSheetList() {
					rows, err := f.GetRows(name)
					if err != nil {
						fmt.Println(err)
						return
					}

					resFieldTypes := ParseSpecialField(rows)

					for k, v := range resFieldTypes {
						allSpecFieldTypes[k] = append(allSpecFieldTypes[k], v...)
					}

				}

				ParseSpecialValues(allSpecFieldTypes, filenameOnly, jsonDir)
				GenSpecialGoFiles(pack, allSpecFieldTypes, filenameOnly, goDir)
			} else {
				for _, name := range f.GetSheetList() {
					if strings.HasPrefix(name, "#") { // 注释sheet跳出
						continue
					}

					nrows, err := f.GetRows(name)
					if err != nil {
						fmt.Println(err)
						return
					}

					if len(nrows) == 0 {
						continue
					}

					if len(nrows) < 3 {
						continue
					}

					rowsLen := len(nrows[0])

					newCols := make([][]string, rowsLen)

					for _, val := range nrows[:3] {
						for num, v := range val {
							if num >= rowsLen {
								continue
							}
							newCols[num] = append(newCols[num], v)
						}
					}

					for num, v := range newCols {
						if len(v) < 3 {
							for i := len(v); i < 3; i++ {
								newCols[num] = append(newCols[num], "")
							}
						}

					}

					resNumsKeys, resFieldTypes := ParseField(newCols)
					if len(resNumsKeys) == 0 {
						continue
					}
					for k, v := range resNumsKeys {
						allKeys[k] = v
					}
					for k, v := range resFieldTypes {
						allFieldTypes[k] = append(allFieldTypes[k], v...)
					}

					rows, err := f.GetRows(name)
					if err != nil {
						fmt.Println(err)
						return
					}
					allData = append(allData, rows[3:]...)

				}
			}

			ParseValues(allData, allKeys, filenameOnly, jsonDir)
			GenTempGoFiles(pack, allFieldTypes, filenameOnly, goDir)
		}(vname)

	}
	wg.Wait()
	// 写自动重载文件
	WriteAutoLoadGoFile(goDir)

	fmt.Println("cost time:", time.Since(startTime).Milliseconds(), "毫秒")
}
